
import os
import threading
import time
from apscheduler.schedulers.blocking import BlockingScheduler
import pytest
import requests
import subprocess
from common.osPath import dirName

from common.sever_email import Sever_email

from common.mysql import mysql



def run_tests_and_generate_report():
    print("开始执行测试用例收集报告")
    #进入文件目录
    os.chdir(r'C:\python\接口\wangjiaxing')
    # os.system('pytest')
    pytest.main()
    os.system('allure generate ./temps -o ./report --clean')
#-----------------------------------------------------------------------#
    #下面进入测试报告文件夹，通过powershell,开启测试anywhere服务打开测试用例，并通过企业机器人发送通过，给相关人发送邮件


    # 使用 Python 改变当前工作目录
    os.chdir(r'C:\python\接口\wangjiaxing\report')

    # 获取当前工作目录
    current_directory = os.getcwd()

     # 继续执行后面的代码...
    print("开启anywhere服务")

    subprocess.run(["powershell", "-Command", current_directory], capture_output=True, text=True, shell=True)

    # 启动 anywhere 进程并将其放入后台执行
    anywhere_process = subprocess.Popen(["powershell", "-Command", "anywhere"], shell=True, stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE, stdin=subprocess.PIPE, start_new_session=True)
    while True:
        # 读取并显示 stdout 的内容
        output_line = anywhere_process.stdout.readline()
        if output_line:
            http_result = output_line.decode('utf-8').strip("Running at")
            print("报告详情连接{}".format(http_result))
            break

        # 读取并显示 stderr 的内容
        error_line = anywhere_process.stderr.readline()
        if error_line:
            print("anywhere 进程错误:", error_line.decode('utf-8').strip())

    #配置文件地址
    config_path = "config\YingXiao.ini"
    #sql配置文件section
    testcase='testcase'
    #连接数据库查询数据,获取用例总数，成功个数，失败个数，测试时间
    db_testcase = mysql(config_path,testcase)
    text='select * from t_testcase_summary where id=1'
    summary=db_testcase.select_all(text)

    webhook_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=7c975a30-87a4-43a2-8568-74522ddc535e"
    headers = {'Content-Type': 'application/json'}

    message = {
        "msgtype": "text",
        "text": {
            "content": "营销, 支付(heampay支付,Qirs支付),转账,VA入金,定存,生活服务充值,登录,7个模块测试用例总数{},通过{}，失败{}，错误{}，测试用时{}，报告详情链接{}".format(summary[1],summary[2],summary[3],summary[4],summary[7],http_result),
            "mentioned_list":["@all"]
        }
    }

    response = requests.post(webhook_url, json=message, headers=headers)
    content= "营销, 支付(heampay支付,Qirs支付),转账,VA入金,定存,生活服务充值,登录,7个模块测试用例总数{},通过{}，失败{}，错误{}，测试用时{}，报告详情链接{}".format(summary[1],summary[2],summary[3],summary[4],summary[7],http_result)
    ssl=Sever_email(config_path,content)
    ssl.smtp_sever()

    print('等待倒计时关闭anywhere')
    time.sleep(36000)
    # 关闭anywhere服务
    subprocess.run(
        ["powershell", "-Command", f"Stop-Process -Id (Get-NetTCPConnection -LocalPort 8000).OwningProcess -Force"],capture_output=True,
        shell=True)
    subprocess.run(
        ["powershell", "-Command", f"Stop-Process -Id (Get-NetTCPConnection -LocalPort 8001).OwningProcess -Force"],capture_output=True,
        shell=True)
    print("anywhere服务已关闭")




def job():
    thread = threading.Thread(target=run_tests_and_generate_report)
    thread.start()






if __name__ == '__main__':
    job()
    scheduler = BlockingScheduler()

    # 每分钟执行一次 job 函数
    scheduler.add_job(job, 'cron', hour=9,minute=30)

    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass



# if __name__ == '__main__':
#     pytest.main()
#     os.system('allure generate ./temps -o ./report --clean')


